﻿using System.Collections.Generic;
using System.Linq;
using hello.csharp.controller;
using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace hello.csharp.zone.Swaggers
{
    /// <summary>
    /// 操作过过滤器 添加通用参数等
    /// </summary>
    public class AssignOperationVendorExtensions : IOperationFilter
    {
        /// <summary>
        /// apply
        /// </summary>
        /// <param name="op"></param>
        /// <param name="context"></param>
        public void Apply(Operation op, OperationFilterContext context)
        {
            if (op == null || context == null)
                return;
            op.Parameters = op.Parameters ?? new List<IParameter>();
            //接口版本
            if (op.Parameters.FirstOrDefault(e => e.Name == "VER") is NonBodyParameter versionInfo)
            {
                op.Parameters.Remove(versionInfo);
                versionInfo.Default = context.ApiDescription.GroupName ?? typeof(ApiVersions).GetEnumNames().LastOrDefault();
                versionInfo.Description = "接口版本";
                op.Parameters.Insert(0, versionInfo);
            }

#pragma warning disable 618
            var attrs = context.ApiDescription.ControllerAttributes().ToArray();
#pragma warning restore 618

            // 需要权限管理的接口（Token)
            var isAuthor = attrs.Any(e => e.GetType() == typeof(AuthorizeAttribute));
            if (isAuthor)
            {
                op.Parameters.Insert(0, new NonBodyParameter()
                {
                    Name = "Token", In = "header", Description = "身份验证票据", Required = true, Type = "string"
                });
            }

            var fileAttr = attrs.OfType<SwaggerFileUploadAttribute>().FirstOrDefault();
            if (fileAttr != null)
            {
                op.Parameters.Add(new NonBodyParameter
                {
                    Name = "file",
                    In = "formData",
                    Description = "上传图片",
                    Required = fileAttr.Required,
                    Type = "file"
                });

            }
        }
    }
}